package com.sxjh.controller.ny;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.cglib.CglibUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sxjh.annotation.UserLog;
import com.sxjh.common.BaseController;
import com.sxjh.common.Constant;
import com.sxjh.common.Result;
import com.sxjh.common.ZPage;
import com.sxjh.config.Authorization;
import com.sxjh.entity.Ic;
import com.sxjh.entity.Task;
import com.sxjh.entity.WagonNumber;
import com.sxjh.entity.param.WagonNumberAddParam;
import com.sxjh.entity.param.WagonNumberListParam;
import com.sxjh.entity.param.WagonNumberUpdateParam;
import com.sxjh.entity.result.WagonNumberListResult;
import com.sxjh.entity.result.WagonNumberSelectResult;
import com.sxjh.enums.DelFlagEnum;
import com.sxjh.service.IcService;
import com.sxjh.service.TaskService;
import com.sxjh.service.WagonNumberService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 * 车号表  前端控制器
 * </p>
 *
 * @author zixin
 * @since 2021-06-05
 */
@RestController
@RequestMapping("/wagon-number")
@Api(tags = "车辆管理")
public class WagonNumberController extends BaseController {

    @Autowired
    private WagonNumberService wagonNumberService;

    @Autowired
    private IcService icService;

    @Autowired
    private TaskService taskService;

    @ApiOperation("列表")
    @GetMapping
    @Authorization("wagon-number.list")
    Result<ZPage<WagonNumberListResult>> list(WagonNumberListParam param) {
        // 根据条件搜索
        IPage iPage = new Page(param.getCurrent(), param.getSize());
        if (param.getSize() == -1) {
            iPage.setSize(Constant.maxSize);
        }
        iPage = wagonNumberService.queryPage(new Page(param.getCurrent(), param.getSize()), param);
        ZPage<WagonNumberListResult> zPage = copyPage(iPage, WagonNumberListResult::new);
        return Result.ok(zPage);
    }

    @ApiOperation("生成派车单的车号列表")
    @GetMapping("task-wagonList")
    @Authorization("wagon-number.list")
    Result<ZPage<WagonNumberListResult>> taskWagonList(WagonNumberListParam param) {
        // 根据条件搜索
        IPage iPage = new Page(param.getCurrent(), param.getSize());
        if (param.getSize() == -1) {
            iPage.setSize(Constant.maxSize);
        }
        iPage = wagonNumberService.taskWagonList(new Page(param.getCurrent(), param.getSize()), param);
        ZPage<WagonNumberListResult> zPage = copyPage(iPage, WagonNumberListResult::new);
        return Result.ok(zPage);
    }

    @ApiOperation("IC卡查询车辆列表")
    @GetMapping("/ic-select")
    Result<ZPage<WagonNumberListResult>> icSelect(WagonNumberListParam param) {
        // 根据条件搜索
        IPage iPage = new Page(param.getCurrent(), param.getSize());
        if (param.getSize() == -1) {
            iPage.setSize(Constant.maxSize);
        }
        iPage = wagonNumberService.icSelect(new Page(param.getCurrent(), param.getSize()), param);
        ZPage<WagonNumberListResult> zPage = copyPage(iPage, WagonNumberListResult::new);
        return Result.ok(zPage);
    }


    @PostMapping
    @ApiOperation("新增")
    @Authorization("wagon-number.add")
    @UserLog(desc = "内部倒运-新增车辆管理", roleCode = "wagon-number.add")
    Result<String> add(@RequestBody @Validated WagonNumberAddParam param) {
        if (new BigDecimal(param.getTare()).compareTo(new BigDecimal(0.1)) != 1) return err("皮重必须大于0.1吨");
        if (new BigDecimal(param.getCapacity()).compareTo(new BigDecimal(param.getTare())) < 0)
            return Result.err("毛重必须大于皮重");
        int count = wagonNumberService.count(new LambdaQueryWrapper<WagonNumber>().eq(WagonNumber::getNumber, param.getNumber()));
        if (count > 0) {
            return Result.err("车牌号已存在!");
        }
        WagonNumber wagonNumber = CglibUtil.copy(param, WagonNumber.class);
        try {
            wagonNumberService.save(wagonNumber);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return Result.err("保存失败，车号已存在或其他异常");
        }
        String record = String.format("车牌号：%s", param.getNumber());
        return Result.ok(record);
    }

    @GetMapping("/delete/{id}")
    @ApiOperation("删除")
    @Authorization("wagon-number.del")
    @UserLog(desc = "内部倒运-删除车辆管理", roleCode = "wagon-number.del")
    Result<String> del(@PathVariable Integer id) {
        int count = icService.count(new LambdaQueryWrapper<Ic>().eq(Ic::getWagonNumberId, id));
        if (count > 0) return Result.err("请先与IC卡解绑才能删除");
        int count2 = taskService.count(new LambdaQueryWrapper<Task>().eq(Task::getWagonNumberId, id));
        if (count2 > 0) return Result.err("请先删除与任务的绑定关系，才能删除该车号");
        WagonNumber wagonNumber = wagonNumberService.getById(id);
        String record = String.format("车牌号：%s", wagonNumber == null ? "" : wagonNumber.getNumber());
        return wagonNumberService.removeById(id) ? Result.ok(record) : Result.err("删除失败！ID不存在或其他异常");
    }

    @PostMapping("/update")
    @ApiOperation("修改")
    @Authorization("wagon-number.update")
    @UserLog(desc = "内部倒运-修改车辆管理", roleCode = "wagon-number.update")
    Result<String> update(@RequestBody @Validated WagonNumberUpdateParam param) {
        if (new BigDecimal(param.getCapacity()).compareTo(new BigDecimal(param.getTare())) != 1)
            return Result.err("载重必须大于皮重");
        int count = wagonNumberService.count(new LambdaQueryWrapper<WagonNumber>().eq(WagonNumber::getNumber, param.getNumber()).ne(WagonNumber::getId, param.getId()));
        if (count > 0) {
            return Result.err("车牌号已存在!");
        }
        WagonNumber wagonNumber = CglibUtil.copy(param, WagonNumber.class);
        WagonNumber queryWagonNumber = wagonNumberService.getById(param.getId());
        String record = String.format("车牌号：%s", queryWagonNumber == null ? "" : queryWagonNumber.getNumber());
        return wagonNumberService.updateById(wagonNumber) ? Result.ok(record) : Result.err("修改失败");
    }

    @GetMapping("/select")
    @ApiOperation("车号下拉框")
    @ApiImplicitParam(value = "车牌号", name = "number")
    Result<List<WagonNumberSelectResult>> select(String number) {
        LambdaQueryWrapper<WagonNumber> wrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotEmpty(number)) wrapper.like(WagonNumber::getNumber, number);
        wrapper.select(WagonNumber::getId, WagonNumber::getNumber);
        List<WagonNumber> list = wagonNumberService.list(wrapper);
        List<WagonNumberSelectResult> results = copyList(list, WagonNumberSelectResult::new);
        return Result.ok(results);
    }

    @ApiOperation("作废")
    @GetMapping(value = "/invalid")
    public Result<Object> delete(@RequestParam("id") String id) {
        WagonNumber params = new WagonNumber();
        params.setId(Integer.valueOf(id));
        params.setDelFlag(DelFlagEnum.YES.getType());
        wagonNumberService.updateById(params);
        return Result.ok(HttpStatus.OK);
    }

}